/*-----------------------------------------------------------------------------

 Copyright 2017 Hopsan Group

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.


 The full license is available in the file LICENSE.
 For details about the 'Hopsan Group' or information about Authors and
 Contributors see the HOPSANGROUP and AUTHORS files that are located in
 the Hopsan source code root directory.

-----------------------------------------------------------------------------*/

#ifndef MECHANICVEHICLE1D_HPP_INCLUDED
#define MECHANICVEHICLE1D_HPP_INCLUDED

#include <iostream>
#include "ComponentEssentials.h"
#include "ComponentUtilities.h"
#include "math.h"

//!
//! @file MechanicVehicle1D.hpp
//! @author Petter Krus <petter.krus@liu.se>
//! @date Thu 12 Feb 2015 13:09:13
//! @brief This is a one dimmensional model of a vehicle
//! @ingroup MechanicComponents
//!
//==This code has been autogenerated using Compgen==
//from 
/*{, C:, HopsanTrunk, componentLibraries, defaultLibrary, \
Special}/MechanicVehicle1D.nb*/

using namespace hopsan;

class MechanicVehicle1D : public ComponentQ
{
private:
     double Mc;
     double cfr;
     double CdA;
     double rwheel;
     double rho;
     Port *mpPmr1;
     Port *mpPmr2;
     double delayParts1[9];
     double delayParts2[9];
     double delayParts3[9];
     double delayParts4[9];
     double delayParts5[9];
     Matrix jacobianMatrix;
     Vec systemEquations;
     Matrix delayedPart;
     int i;
     int iter;
     int mNoiter;
     double jsyseqnweight[4];
     int order[5];
     int mNstep;
     //Port Pmr1 variable
     double tormr1;
     double thetamr1;
     double wmr1;
     double cmr1;
     double Zcmr1;
     double eqInertiamr1;
     //Port Pmr2 variable
     double tormr2;
     double thetamr2;
     double wmr2;
     double cmr2;
     double Zcmr2;
     double eqInertiamr2;
//==This code has been autogenerated using Compgen==
     //inputVariables
     //outputVariables
     double vc;
     double xc;
     double fd;
     double fr;
     //LocalExpressions variables
     double fc;
     double Br;
     double fre;
     //Expressions variables
     //Port Pmr1 pointer
     double *mpND_tormr1;
     double *mpND_thetamr1;
     double *mpND_wmr1;
     double *mpND_cmr1;
     double *mpND_Zcmr1;
     double *mpND_eqInertiamr1;
     //Port Pmr2 pointer
     double *mpND_tormr2;
     double *mpND_thetamr2;
     double *mpND_wmr2;
     double *mpND_cmr2;
     double *mpND_Zcmr2;
     double *mpND_eqInertiamr2;
     //Delay declarations
//==This code has been autogenerated using Compgen==
     //inputVariables pointers
     //inputParameters pointers
     double *mpMc;
     double *mpcfr;
     double *mpCdA;
     double *mprwheel;
     double *mprho;
     //outputVariables pointers
     double *mpvc;
     double *mpxc;
     double *mpfd;
     double *mpfr;
     Delay mDelayedPart10;
     Delay mDelayedPart11;
     Delay mDelayedPart20;
     Delay mDelayedPart21;
     Delay mDelayedPart30;
     Delay mDelayedPart31;
     EquationSystemSolver *mpSolver;

public:
     static Component *Creator()
     {
        return new MechanicVehicle1D();
     }

     void configure()
     {
//==This code has been autogenerated using Compgen==

        mNstep=9;
        jacobianMatrix.create(5,5);
        systemEquations.create(5);
        delayedPart.create(6,6);
        mNoiter=2;
        jsyseqnweight[0]=1;
        jsyseqnweight[1]=0.67;
        jsyseqnweight[2]=0.5;
        jsyseqnweight[3]=0.5;


        //Add ports to the component
        mpPmr1=addPowerPort("Pmr1","NodeMechanicRotational");
        mpPmr2=addPowerPort("Pmr2","NodeMechanicRotational");
        //Add inputVariables to the component

        //Add inputParammeters to the component
            addInputVariable("Mc", "Vehicle inertia at", "kg", 1000.,&mpMc);
            addInputVariable("cfr", "C roll. resist.coeff.", "N/N", \
0.02,&mpcfr);
            addInputVariable("CdA", "effective front area", "m2", \
0.5,&mpCdA);
            addInputVariable("rwheel", "wheel radius", "m", 1.,&mprwheel);
            addInputVariable("rho", "air density", "kg/m3", 1.25,&mprho);
        //Add outputVariables to the component
            addOutputVariable("vc","Vehicle speed","m/s",0.,&mpvc);
            addOutputVariable("xc","Vehicle position","m",0.,&mpxc);
            addOutputVariable("fd","Aerodynamc drag","N",0.,&mpfd);
            addOutputVariable("fr","Rolling resistance","N",0.,&mpfr);

//==This code has been autogenerated using Compgen==
        //Add constantParameters
        mpSolver = new EquationSystemSolver(this,5);
     }

    void initialize()
     {
        //Read port variable pointers from nodes
        //Port Pmr1
        mpND_tormr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::Torque);
        mpND_thetamr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::Angle);
        mpND_wmr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::AngularVelocity);
        mpND_cmr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::WaveVariable);
        mpND_Zcmr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::CharImpedance);
        mpND_eqInertiamr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::EquivalentInertia);
        //Port Pmr2
        mpND_tormr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::Torque);
        mpND_thetamr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::Angle);
        mpND_wmr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::AngularVelocity);
        mpND_cmr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::WaveVariable);
        mpND_Zcmr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::CharImpedance);
        mpND_eqInertiamr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::EquivalentInertia);

        //Read variables from nodes
        //Port Pmr1
        tormr1 = (*mpND_tormr1);
        thetamr1 = (*mpND_thetamr1);
        wmr1 = (*mpND_wmr1);
        cmr1 = (*mpND_cmr1);
        Zcmr1 = (*mpND_Zcmr1);
        eqInertiamr1 = (*mpND_eqInertiamr1);
        //Port Pmr2
        tormr2 = (*mpND_tormr2);
        thetamr2 = (*mpND_thetamr2);
        wmr2 = (*mpND_wmr2);
        cmr2 = (*mpND_cmr2);
        Zcmr2 = (*mpND_Zcmr2);
        eqInertiamr2 = (*mpND_eqInertiamr2);

        //Read inputVariables from nodes

        //Read inputParameters from nodes
        Mc = (*mpMc);
        cfr = (*mpcfr);
        CdA = (*mpCdA);
        rwheel = (*mprwheel);
        rho = (*mprho);

        //Read outputVariables from nodes
        vc = (*mpvc);
        xc = (*mpxc);
        fd = (*mpfd);
        fr = (*mpfr);

//==This code has been autogenerated using Compgen==

        //LocalExpressions
        fd = (CdA*rho*vc*Abs(vc))/2.;
        fc = 9.82*cfr*Mc;
        Br = Mc/mTimestep;
        fre = limit(Br*vc,-fc,fc);

        //Initialize delays
        delayParts1[1] = (fd*mTimestep*rwheel + fre*mTimestep*rwheel - \
mTimestep*tormr1 - mTimestep*tormr2 - 2*Mc*rwheel*vc)/(2.*Mc*rwheel);
        mDelayedPart11.initialize(mNstep,delayParts1[1]);
        delayParts2[1] = (-(mTimestep*vc) - 2*xc)/2.;
        mDelayedPart21.initialize(mNstep,delayParts2[1]);
        delayParts3[1] = (-2*rwheel*thetamr1 - mTimestep*vc)/(2.*rwheel);
        mDelayedPart31.initialize(mNstep,delayParts3[1]);

        delayedPart[1][1] = delayParts1[1];
        delayedPart[2][1] = delayParts2[1];
        delayedPart[3][1] = delayParts3[1];
        delayedPart[4][1] = delayParts4[1];
        delayedPart[5][1] = delayParts5[1];
     }
    void simulateOneTimestep()
     {
        Vec stateVar(5);
        Vec stateVark(5);
        Vec deltaStateVar(5);

        //Read variables from nodes
        //Port Pmr1
        cmr1 = (*mpND_cmr1);
        Zcmr1 = (*mpND_Zcmr1);
        //Port Pmr2
        cmr2 = (*mpND_cmr2);
        Zcmr2 = (*mpND_Zcmr2);

        //Read inputVariables from nodes

        //Read inputParameters from nodes
        Mc = (*mpMc);
        cfr = (*mpcfr);
        CdA = (*mpCdA);
        rwheel = (*mprwheel);
        rho = (*mprho);

        //LocalExpressions
        fd = (CdA*rho*vc*Abs(vc))/2.;
        fc = 9.82*cfr*Mc;
        Br = Mc/mTimestep;
        fre = limit(Br*vc,-fc,fc);

        //Initializing variable vector for Newton-Raphson
        stateVark[0] = vc;
        stateVark[1] = xc;
        stateVark[2] = thetamr1;
        stateVark[3] = tormr1;
        stateVark[4] = tormr2;

        //Iterative solution using Newton-Rapshson
        for(iter=1;iter<=mNoiter;iter++)
        {
         //Vehicle1D
         //Differential-algebraic system of equation parts

          //Assemble differential-algebraic equations
          systemEquations[0] =(mTimestep*(fd*rwheel + fre*rwheel - tormr1 - \
tormr2))/(2.*Mc*rwheel) + vc + delayedPart[1][1];
          systemEquations[1] =-(mTimestep*vc)/2. + xc + delayedPart[2][1];
          systemEquations[2] =thetamr1 - (mTimestep*vc)/(2.*rwheel) + \
delayedPart[3][1];
          systemEquations[3] =-cmr1 + tormr1 + (vc*Zcmr1)/rwheel;
          systemEquations[4] =-cmr2 + tormr2 + (vc*Zcmr2)/rwheel;

          //Jacobian matrix
          jacobianMatrix[0][0] = 1;
          jacobianMatrix[0][1] = 0;
          jacobianMatrix[0][2] = 0;
          jacobianMatrix[0][3] = -mTimestep/(2.*Mc*rwheel);
          jacobianMatrix[0][4] = -mTimestep/(2.*Mc*rwheel);
          jacobianMatrix[1][0] = -mTimestep/2.;
          jacobianMatrix[1][1] = 1;
          jacobianMatrix[1][2] = 0;
          jacobianMatrix[1][3] = 0;
          jacobianMatrix[1][4] = 0;
          jacobianMatrix[2][0] = -mTimestep/(2.*rwheel);
          jacobianMatrix[2][1] = 0;
          jacobianMatrix[2][2] = 1;
          jacobianMatrix[2][3] = 0;
          jacobianMatrix[2][4] = 0;
          jacobianMatrix[3][0] = Zcmr1/rwheel;
          jacobianMatrix[3][1] = 0;
          jacobianMatrix[3][2] = 0;
          jacobianMatrix[3][3] = 1;
          jacobianMatrix[3][4] = 0;
          jacobianMatrix[4][0] = Zcmr2/rwheel;
          jacobianMatrix[4][1] = 0;
          jacobianMatrix[4][2] = 0;
          jacobianMatrix[4][3] = 0;
          jacobianMatrix[4][4] = 1;
//==This code has been autogenerated using Compgen==

          //Solving equation using LU-faktorisation
          mpSolver->solve(jacobianMatrix, systemEquations, stateVark, iter);
          vc=stateVark[0];
          xc=stateVark[1];
          thetamr1=stateVark[2];
          tormr1=stateVark[3];
          tormr2=stateVark[4];
          //Expressions
          wmr1 = -(vc/rwheel);
          wmr2 = -(vc/rwheel);
          thetamr2 = thetamr1;
          fr = fre;
          eqInertiamr1 = Mc*Power(rwheel,2);
          eqInertiamr2 = Mc*Power(rwheel,2);
        }

        //Calculate the delayed parts
        delayParts1[1] = (fd*mTimestep*rwheel + fre*mTimestep*rwheel - \
mTimestep*tormr1 - mTimestep*tormr2 - 2*Mc*rwheel*vc)/(2.*Mc*rwheel);
        delayParts2[1] = (-(mTimestep*vc) - 2*xc)/2.;
        delayParts3[1] = (-2*rwheel*thetamr1 - mTimestep*vc)/(2.*rwheel);

        delayedPart[1][1] = delayParts1[1];
        delayedPart[2][1] = delayParts2[1];
        delayedPart[3][1] = delayParts3[1];
        delayedPart[4][1] = delayParts4[1];
        delayedPart[5][1] = delayParts5[1];

        //Write new values to nodes
        //Port Pmr1
        (*mpND_tormr1)=tormr1;
        (*mpND_thetamr1)=thetamr1;
        (*mpND_wmr1)=wmr1;
        (*mpND_eqInertiamr1)=eqInertiamr1;
        //Port Pmr2
        (*mpND_tormr2)=tormr2;
        (*mpND_thetamr2)=thetamr2;
        (*mpND_wmr2)=wmr2;
        (*mpND_eqInertiamr2)=eqInertiamr2;
        //outputVariables
        (*mpvc)=vc;
        (*mpxc)=xc;
        (*mpfd)=fd;
        (*mpfr)=fr;

        //Update the delayed variabels
        mDelayedPart11.update(delayParts1[1]);
        mDelayedPart21.update(delayParts2[1]);
        mDelayedPart31.update(delayParts3[1]);

     }
    void deconfigure()
    {
        delete mpSolver;
    }
};
#endif // MECHANICVEHICLE1D_HPP_INCLUDED
